#include <cstdio>
#include <iostream>
#include <pthread.h>
#include <type_traits>
#include <unistd.h>
#include <vector>
using namespace std;
#define N 5
int cnt = 100;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* func(void* args) {
    string name = static_cast<const char* >(args);
    while (true) {
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond, &lock);
        cout << name << "计算" << cnt++ << endl;
        pthread_mutex_unlock(&lock);
    }
    return nullptr;
}
int main() {
    vector<pthread_t> threads;
    for(int i = 0; i < N; i++) {
        pthread_t tid;
        char* name = new char[64];
        snprintf(name, 64, "thread_%d", i);
        int temp = pthread_create(&tid, nullptr, func, (void*)name);
        if(temp != 0) {
            continue;
        }
        threads.push_back(tid);
        sleep(1);
    }
    // sleep(5);
    while (true) {
        cout << "唤醒所有的线程..." << endl;
        pthread_cond_broadcast(&cond);
        // cout << "唤醒出一个线程..." << endl;
        // pthread_cond_signal(&cond);
        sleep(1);
    }
    for(auto& e : threads) {
        int temp = pthread_join(e, nullptr);
        (void)temp;
    }
    return 0;
}